package com.ruizhong.centercontroll.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ruizhong.centercontroll.aspect.myAnnotation.checkLogin;
import com.ruizhong.centercontroll.entity.TPage;
import com.ruizhong.centercontroll.server.WebSocketServer;
import com.ruizhong.centercontroll.service.TPageService;
import com.ruizhong.centercontroll.util.Result;
import com.ruizhong.centercontroll.util.ResultCode;
import com.ruizhong.centercontroll.util.TCPSender;
import com.ruizhong.centercontroll.util.XmlPageMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.JAXBException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/page/api")
@CrossOrigin
public class TPageController {

    @Autowired
    private TPageService tPageService;

    @PostMapping("/saveNewPage")
    @checkLogin("saveNewPage")
    public Result saveNewPage(@RequestBody TPage tPage) {
        Integer pageId = tPageService.saveNewPage(tPage);
        return new Result(ResultCode.success, "保存成功", pageId);
    }

    @GetMapping("/getPageInfoByPageName/{pageName}")
//    @checkLogin("getPageInfoByPageName")
    public Result getPageInfoByPageName(@PathVariable(value = "pageName") String pageName) {
        TPage pageInfo = tPageService.getPageInfoByPageName(pageName);
        return new Result(ResultCode.success, null, pageInfo);
    }

    @PostMapping("/saveAllComponents/{pageId}/{token}/{isNew}")
    @checkLogin
    public Result saveAllComponents(
            @RequestBody Map<String, List<Map<String, Object>>> conditionMap,
            @PathVariable(value = "pageId") Integer pageId,
            @PathVariable(value = "token") String token,
            @PathVariable(value = "isNew") String isNew) {
        tPageService.saveAllComponents(conditionMap, pageId, token, isNew.equals("true"));
        return new Result(ResultCode.success, "组件保存成功", null);
    }

    @GetMapping("/getAllComponentByPageName/{pageName}/{aimPageWidth}/{aimPageHeight}/{Display}")
//    @checkLogin
    public Result getAllComponentByPageName(
            @PathVariable(value = "pageName") String pageName,
            @PathVariable(value = "aimPageWidth") Double aimPageWidth,
            @PathVariable(value = "aimPageHeight") Double aimPageHeight,
            @PathVariable(value = "Display") Boolean display) throws JsonProcessingException {
        Map<String, Object> allComponentByPageName = tPageService.getAllComponentByPageName(
                pageName,
                aimPageWidth,
                aimPageHeight,
                display
        );
        return new Result(ResultCode.success, null, allComponentByPageName);
    }

    @GetMapping("/disconnectPage/{tokenId}/{pageName}")
    @checkLogin
    public Result disconnectPage(@PathVariable(value = "tokenId") String randomId, @PathVariable(value = "pageName") String pageName) throws IOException {
        Set<String> webSocketServers = WebSocketServer.pathMapClient.get(pageName);
        if (CollectionUtils.isEmpty(webSocketServers)) {
            return new Result(ResultCode.success, null, null);
        }
        webSocketServers.remove(randomId);
        TCPSender.closeTCPConnection(randomId);
        WebSocketServer webSocketServer = WebSocketServer.webSocketMap.get(randomId);
        webSocketServer.getSession().close();
        return new Result(ResultCode.success, null, null);
    }

    @PostMapping("/updatePage")
    @checkLogin("updatePage")
    public Result updatePage(@RequestBody TPage tPage) {
        tPageService.updatePage(tPage);
        return new Result(ResultCode.success, null, tPage.getId());
    }

    @GetMapping("/getAllPages")
    @checkLogin("getAllPages")
    public Result getAllPages() {
        List<TPage> pages = tPageService.getAllPages();
        return new Result(ResultCode.success, null, pages);
    }

    @PostMapping("/outputComponentFormat")
    @checkLogin
    public ResponseEntity<InputStreamResource> outputComponentFormat() {
        // 这里我们创建一个简单的CSV文件内容
        String csvContent = "id,name,email\n1,John Doe,john@example.com\n2,Jane Doe,jane@example.com";

        // 将字符串转换为输入流
        InputStreamResource resource = new InputStreamResource(
                new ByteArrayInputStream(csvContent.getBytes(StandardCharsets.UTF_8)));

        // 设置HTTP头部信息
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=users.csv")
                .contentType(MediaType.parseMediaType("text/csv"))
                .contentLength(csvContent.getBytes(StandardCharsets.UTF_8).length)
                .body(resource);
    }

    @DeleteMapping("/delPageByPageId/{pageId}")
    @checkLogin("delPageByPageId")
    public Result delPageByPageId(@PathVariable(value = "pageId") Integer pageId) {
        tPageService.delPageByPageId(pageId);
        return new Result(ResultCode.success, "删除成功", null);
    }

    @PostMapping("/initPage/{pageName}/{tokenId}")
    public Result initPage(
            @PathVariable(value = "pageName") String pageName,
            @PathVariable(value = "tokenId") String tokenId,
            @RequestBody Map<String, Object> variableSet,
            HttpServletRequest request
    ) {
        String ip = CommandController.getClientIp(request);
        synchronized (ip.intern()) {
            ConcurrentHashMap.KeySetView<String, String> ips = CommandController.runMap.keySet();
            if (ips.contains(ip)){
                throw new RuntimeException("命令执行中");
            }
            CommandController.runMap.put(ip,"");
        }
        Integer pageId = tPageService.getPageIdByPageName(pageName);
        tPageService.initPage(pageId, tokenId, (Map<String, Object>) variableSet.get("variableSet"),ip);
        return new Result(ResultCode.success, null, null);
    }

    @PostMapping("/updatePageImg")
    @checkLogin
    public Result updatePageImg(@RequestBody Map<String, String> conditionMap) {
        tPageService.updatePageImg(conditionMap);
        return new Result(ResultCode.success, null, null);
    }

    @PostMapping("/outputPage")
    @checkLogin
    public ResponseEntity<InputStreamResource> outputPage(String pageName) throws JAXBException, JsonProcessingException {
        return tPageService.outputPage(pageName);
    }

    @PostMapping("/ImportPageXmlTemplate")
    @checkLogin
    public Result ImportPageXmlTemplate(@RequestBody MultipartFile file) {
        XmlPageMap xmlPageMap = tPageService.ImportPageXmlTemplate(file);
        return new Result(ResultCode.success, "导入成功", xmlPageMap);
    }

}
